<template>
  <div class="user-management-container">
    <!-- 搜索区域 -->
    <el-card shadow="never">
      <el-form :inline="true" :model="searchParams" @submit.prevent="handleSearch">
        <el-form-item label="用户ID">
          <el-input v-model="searchParams.id" placeholder="精确查找ID" clearable />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="searchParams.username" placeholder="模糊搜索用户名" clearable />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchParams.phone" placeholder="搜索手机号" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleSearch">搜索</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 表格区域 -->
    <el-card shadow="never" style="margin-top: 20px;">
      <el-table :data="userList" v-loading="loading" border style="width: 100%">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" />
        <el-table-column prop="email" label="邮箱" show-overflow-tooltip />
        <el-table-column prop="phone" label="手机号" />
        <el-table-column prop="address" label="地址" show-overflow-tooltip />
        <el-table-column label="操作" width="320" align="center">
          <template #default="{ row }">
            <el-button type="primary" link :icon="Edit" @click="openEditDialog(row)">修改</el-button>
            <el-button type="success" link :icon="Coin" @click="openRechargeDialog(row)">充值</el-button>
            <el-button type="danger" link :icon="RefreshLeft" @click="handleResetPassword(row)">重置密码</el-button>
            <el-button type="warning" link :icon="Lock" @click="handleResetPaymentPassword(row)">重置支付密码</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 修改用户信息弹窗 -->
    <el-dialog v-model="editDialog.visible" title="修改用户信息" width="500px">
      <el-form :model="editDialog.form" label-width="80px" ref="editFormRef">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editDialog.form.username" />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="editDialog.form.newPassword" type="password" show-password placeholder="留空则不修改" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editDialog.form.email" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="editDialog.form.phone" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editDialog.form.address" type="textarea" />
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="editDialog.form.description" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="editDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitEditForm">确认修改</el-button>
      </template>
    </el-dialog>

    <!-- 充值弹窗 -->
    <el-dialog v-model="rechargeDialog.visible" title="为用户充值" width="400px">
      <el-form :model="rechargeDialog.form" label-width="80px" ref="rechargeFormRef">
        <el-form-item label="用户名">
          <el-input :value="rechargeDialog.username" disabled />
        </el-form-item>
        <el-form-item label="当前余额">
          <el-input :value="`¥ ${rechargeDialog.currentBalance || 0}`" disabled />
        </el-form-item>
        <el-form-item label="充值金额" prop="amount">
          <el-input-number v-model="rechargeDialog.form.amount" :min="0.01" :precision="2" controls-position="right" style="width: 100%;" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="rechargeDialog.visible = false">取消</el-button>
        <el-button type="primary" @click="submitRechargeForm">确认充值</el-button>
      </template>
    </el-dialog>

  </div>
</template>

<script setup lang="js">
import { ref, reactive, onMounted } from 'vue';
import { Search, Edit, Coin, RefreshLeft, Lock } from '@element-plus/icons-vue';
import {
  searchUsers,
  updateUserInfo,
  rechargeForUser,
  resetUserPassword,
  resetUserPaymentPassword
} from '@/api/admin/user';
import { ElMessage, ElMessageBox } from 'element-plus';

// --- 数据定义 ---
const loading = ref(false);

const searchParams = reactive({
  id: '',
  username: '',
  phone: ''
});

const userList = ref([]);

const editDialog = reactive({
  visible: false,
  form: {
    userId: null,
    username: '',
    newPassword: '', // 登录密码
    email: '',
    phone: '',
    address: '',
    description: ''
  }
});

const rechargeDialog = reactive({
  visible: false,
  username: '',
  currentBalance: 0, // 用于显示当前余额
  form: {
    targetUserId: null,
    amount: 100
  }
});

// --- 方法定义 ---

const handleSearch = async () => {
  loading.value = true;
  try {
    const res = await searchUsers(searchParams);
    // 你的后端可能成功时是字符串'200'，失败是数字，我们用宽松等于来兼容
    if (res.code == 200) {
      userList.value = res.data;
    } else {
      userList.value = []; // 搜索失败或无结果时清空列表
      ElMessage.error(res.message || res.msg || '搜索失败');
    }
  } catch (error) {
    console.error("搜索用户失败:", error);
    ElMessage.error('网络请求失败，请检查后端服务或网络连接');
  } finally {
    loading.value = false;
  }
};

const openEditDialog = (row) => {
  editDialog.form.userId = row.id;
  editDialog.form.username = row.username;
  editDialog.form.newPassword = ''; // 密码不回显
  editDialog.form.email = row.email;
  editDialog.form.phone = row.phone;
  editDialog.form.address = row.address;
  editDialog.form.description = row.description;
  editDialog.visible = true;
};

const submitEditForm = async () => {
  const res = await updateUserInfo(editDialog.form);
  if (res.code == 200) {
    ElMessage.success('用户信息更新成功！');
    editDialog.visible = false;
    handleSearch();
  } else {
    ElMessage.error(res.message || res.msg || '更新失败');
  }
};

const openRechargeDialog = (row) => {
  rechargeDialog.username = row.username;
  rechargeDialog.form.targetUserId = row.id;
  rechargeDialog.currentBalance = row.money;
  rechargeDialog.form.amount = 100;
  rechargeDialog.visible = true;
};

const submitRechargeForm = async () => {
  if (!rechargeDialog.form.amount || rechargeDialog.form.amount <= 0) {
    ElMessage.warning('请输入有效的充值金额');
    return;
  }
  const res = await rechargeForUser(rechargeDialog.form);
  if (res.code == 200) {
    ElMessage.success(`为用户 ${rechargeDialog.username} 充值成功！`);
    rechargeDialog.visible = false;
    handleSearch();
  } else {
    ElMessage.error(res.message || res.msg || '充值失败');
  }
}

const handleResetPassword = (row) => {
  ElMessageBox.confirm(
      `确定要将用户【${row.username}】的登录密码重置为空吗？`,
      '高危操作确认',
      { type: 'warning' }
  ).then(async () => {
    const res = await resetUserPassword({ userId: row.id });
    if (res.code == 200) {
      ElMessage.success('登录密码重置成功！');
    } else {
      ElMessage.error(res.message || res.msg || '操作失败');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

const handleResetPaymentPassword = (row) => {
  ElMessageBox.prompt(
      `正在为用户【${row.username}】重置支付密码，请输入新的支付密码：`,
      '重置支付密码',
      {
        confirmButtonText: '确认重置',
        cancelButtonText: '取消',
        inputType: 'password',
        inputValidator: (value) => {
          if (!value || value.trim().length === 0) return '新支付密码不能为空！';
          if (value.trim().length < 6) return '支付密码长度不能少于6位！';
          return true;
        },
      }
  ).then(async ({ value }) => {
    const res = await resetUserPaymentPassword({ userId: row.id, newPassword: value });
    if (res.code == 200) {
      ElMessage.success(`用户 ${row.username} 的支付密码重置成功！`);
    } else {
      ElMessage.error(res.message || res.msg || '重置失败，请稍后重试');
    }
  }).catch(() => {
    ElMessage.info('已取消重置支付密码操作');
  });
};

onMounted(() => {
  handleSearch();
});
</script>

<style scoped>
.user-management-container {
  padding: 20px;
}
.el-card {
  border-radius: 8px;
}
</style>